package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    //发送短信
    @Override
    public void sendSms(String phone) {
        //1.生成6位数验证码
        //todo 为了开发测试方便,临时写死验证码
        //String code = RandomUtil.randomNumbers(6);
        String code = "123";
        System.out.println("生成的验证码是:" + code);
        //2.调用redis保存
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        //3.调用阿里云发送
        //todo 开发期间,为了省钱,暂时注释
        //smsTemplate.sendSms(phone,code);
    }
    //注册登录
    @Override
    public ResultInfo login(String phone, String code) {
        //1.获取redis的验证码，跟用户输入的不匹配时，返回错误信息
        String codeFromRedis=(String) redisTemplate.opsForValue().get(phone);
        if (!StringUtils.equals(code, codeFromRedis)) {
            return ResultInfo.error("验证码错误");
        }
        //2.查询手机号在数据库是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = userMapper.selectOne(wrapper);
        //3.user不为空，则表示登录，并登陆成功
        if (user != null) {
            if (user.getStatus() != 1) {    //状态不为1时，返回错误信息
                return ResultInfo.error("用户被冻结，无法登录");
            }
        }else {
            //4.user为空时，表示注册，将手机号存入,并设置状态
            user=new User();    //进入此分支表示user为空，需要创建
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }
        //5.创建token，保存到redis并设置有效期
        Map map = new HashMap();
        map.put("id",user.getId());
        String token = JwtUtil.createToken(map);
        redisTemplate.opsForValue().set("TOKEN_"+token,user,1,TimeUnit.DAYS);
        //6.返回
        return ResultInfo.success(token);
    }
    //退出
    @Override
    public void logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
    }
}
